package com.smartlazy.delay.queue.core.timer;

import com.smartlazy.delay.queue.core.config.DelayQueueProperties;
import com.smartlazy.delay.queue.core.constant.CommonConst;
import com.smartlazy.delay.queue.core.service.DelayBucket;
import com.smartlazy.delay.queue.core.service.DelayJob;
import com.smartlazy.delay.queue.core.service.ReadyQueue;
import lombok.Data;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author howe
 */
@Data
@Service
public class Timer {

    private DelayBucket delayBucket;

    private DelayJob delayJob;

    private ReadyQueue readyQueue;

    private DelayQueueProperties delayQueueProperties;

    /**
     * 扫描bucket, 取出延迟时间小于当前时间的Job
     */
    public void initTimer() {
        ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build());
        int bucketSize = CommonConst.DEFAULT_BUCKET_SIZE;
        if (delayQueueProperties.getBucketSize() != null) {
            bucketSize = delayQueueProperties.getBucketSize().intValue();
        }
        for (int i = 0; i < bucketSize; i++) {
            // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
            service.scheduleAtFixedRate(new TickHandler(CommonConst.DEFAULT_BUCKET_KEY + i,
                            delayBucket, delayJob, readyQueue),
                    10,
                    1,
                    TimeUnit.SECONDS);
        }
    }
}
